package com.example.heimashop.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.heimashop.model.CartItem;

import java.util.ArrayList;
import java.util.List;

/**
 * 购物车数据访问类
 */
public class CartDao {
    private DatabaseHelper dbHelper;

    public CartDao(Context context) {
        this.dbHelper = DatabaseHelper.getInstance(context);
    }

    /**
     * 添加商品到购物车
     */
    public long addToCart(CartItem item) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        // 先检查是否已存在相同商品
        CartItem existingItem = findByGoodsId(item.getGoodsId());
        if (existingItem != null) {
            // 商品已存在，更新数量
            return updateCount(existingItem.getId(), existingItem.getGoodsCount() + item.getGoodsCount());
        }

        // 新商品，插入数据库
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_GOODS_ID, item.getGoodsId());
        values.put(DatabaseHelper.COLUMN_GOODS_NAME, item.getGoodsName());
        values.put(DatabaseHelper.COLUMN_GOODS_PRICE, item.getGoodsPrice());
        values.put(DatabaseHelper.COLUMN_GOODS_IMAGE, item.getGoodsImage());
        values.put(DatabaseHelper.COLUMN_GOODS_COUNT, item.getGoodsCount());
        values.put(DatabaseHelper.COLUMN_IS_CHECKED, item.isChecked() ? 1 : 0);

        return db.insert(DatabaseHelper.TABLE_CART, null, values);
    }

    /**
     * 根据商品ID查找购物车项
     */
    public CartItem findByGoodsId(int goodsId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_CART,
                null,
                DatabaseHelper.COLUMN_GOODS_ID + " = ?",
                new String[]{String.valueOf(goodsId)},
                null, null, null);

        CartItem item = null;
        if (cursor.moveToFirst()) {
            item = cursorToCartItem(cursor);
        }
        cursor.close();
        return item;
    }

    /**
     * 获取所有购物车商品
     */
    public List<CartItem> getAllCartItems() {
        List<CartItem> items = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_CART,
                null, null, null, null, null,
                DatabaseHelper.COLUMN_CART_ID + " DESC");

        while (cursor.moveToNext()) {
            items.add(cursorToCartItem(cursor));
        }
        cursor.close();
        return items;
    }

    /**
     * 更新商品数量
     */
    public int updateCount(int id, int count) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_GOODS_COUNT, count);

        return db.update(DatabaseHelper.TABLE_CART,
                values,
                DatabaseHelper.COLUMN_CART_ID + " = ?",
                new String[]{String.valueOf(id)});
    }

    /**
     * 更新选中状态
     */
    public int updateChecked(int id, boolean checked) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_IS_CHECKED, checked ? 1 : 0);

        return db.update(DatabaseHelper.TABLE_CART,
                values,
                DatabaseHelper.COLUMN_CART_ID + " = ?",
                new String[]{String.valueOf(id)});
    }

    /**
     * 全选/取消全选
     */
    public int updateAllChecked(boolean checked) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_IS_CHECKED, checked ? 1 : 0);

        return db.update(DatabaseHelper.TABLE_CART, values, null, null);
    }

    /**
     * 删除购物车项
     */
    public int deleteCartItem(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        return db.delete(DatabaseHelper.TABLE_CART,
                DatabaseHelper.COLUMN_CART_ID + " = ?",
                new String[]{String.valueOf(id)});
    }

    /**
     * 删除选中的商品
     */
    public int deleteCheckedItems() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        return db.delete(DatabaseHelper.TABLE_CART,
                DatabaseHelper.COLUMN_IS_CHECKED + " = ?",
                new String[]{"1"});
    }

    /**
     * 获取购物车总数
     */
    public int getCartCount() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + DatabaseHelper.TABLE_CART, null);
        int count = 0;
        if (cursor.moveToFirst()) {
            count = cursor.getInt(0);
        }
        cursor.close();
        return count;
    }

    /**
     * 清空购物车
     */
    public int clearCart() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        return db.delete(DatabaseHelper.TABLE_CART, null, null);
    }

    /**
     * 将Cursor转换为CartItem对象
     */
    private CartItem cursorToCartItem(Cursor cursor) {
        CartItem item = new CartItem();
        item.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CART_ID)));
        item.setGoodsId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_GOODS_ID)));
        item.setGoodsName(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_GOODS_NAME)));
        item.setGoodsPrice(cursor.getDouble(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_GOODS_PRICE)));
        item.setGoodsImage(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_GOODS_IMAGE)));
        item.setGoodsCount(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_GOODS_COUNT)));
        item.setChecked(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_IS_CHECKED)) == 1);
        return item;
    }
}
